package org.jiuling.netty.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import org.jiuling.netty.handler.service.HeartBeatHandlerService;

/**
 * 心跳处理器
 * @author 紫灵
 * @date 2025年07月11日 11时37分55秒
 */
public class WebSocketHeartBeatHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    /** 心跳处理服务 */
    private final HeartBeatHandlerService heartBeatHandlerService;

    public WebSocketHeartBeatHandler(HeartBeatHandlerService heartBeatHandlerService) {
        this.heartBeatHandlerService = heartBeatHandlerService;
    }


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame frame) throws Exception {
        channelHandlerContext.fireChannelRead(frame.retain());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent idleStateEvent) {
            switch (idleStateEvent.state()){
                // 读超时
                case READER_IDLE -> heartBeatHandlerService.readWaitTimeout(ctx.channel());
                // 写超时
                case WRITER_IDLE -> heartBeatHandlerService.writeWaitTimeout(ctx.channel());
                // 读写超时
                case ALL_IDLE -> heartBeatHandlerService.allWaitTimeout(ctx.channel());
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
